﻿using AiBLSmartEdu.Module.AIMedicalAssistant.API.DTOs;
using AutoMapper;
using Domain.Entities;
using FrameworkCore.DI;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Interfaces;
using FrameworkCore.Models;
using FrameworkCore.Repositories;

#nullable disable

namespace AiBLSmartEdu.Module.AIMedicalAssistant.API.Services;

/// <summary>
/// 对话管理服务
/// </summary>
public class DialogueService : IScopedDependency
{

    private readonly IRepository<Dialogue> _dialogueRepository; 
    private readonly IRepository<MedicalQuestionAnswerPairs> _medicalQuestionAnswerPairsRepository;
    private readonly ICurrentUserService _currentUserService;
    private readonly IMapper _mapper;

    public DialogueService(
        IRepository<Dialogue> dialogueRepository, 
        IRepository<MedicalQuestionAnswerPairs> medicalQuestionAnswerPairsRepository, 
        ICurrentUserService currentUserService, 
        IMapper mapper)
    {
        _dialogueRepository = dialogueRepository;
        _medicalQuestionAnswerPairsRepository = medicalQuestionAnswerPairsRepository;
        _currentUserService = currentUserService;
        _mapper = mapper;
    }


    /// <summary>
    /// 创建对话标题
    /// </summary>
    /// <param name="title"></param>
    /// <returns></returns>
    public async Task CreateAsync(string title)
    {
        ExceptionHelper.ThrowIfNullOrWhiteSpace(title, $"标题不能为空：{nameof(title)}");

        var exist = _dialogueRepository.Query(x => x.Title == title && _currentUserService.UserId == x.CreatedBy).Any();
        ExceptionHelper.ThrowIfTrue(exist, $"对话标题重复：{title}");

        await _dialogueRepository.InsertAsync(new Dialogue { Title = title });
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<DialogueOutputModel>> PageAsync(DialoguePaginationFilter filter)
    {
        return (await _dialogueRepository.GetOrderedQueryable(query =>
        {
            return query.OrderByDescending(o => o.Id)
            .WhereIf(!filter.Keyword.IsNullOrWhiteSpace(), x => x.Title.Contains(filter.Keyword));

        }, filter).ProjectToPaginatedDataAsync<Dialogue, DialogueOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    /// <summary>
    /// 删除对话
    /// </summary>
    /// <param name="dialogueId">对话唯一标识</param>
    /// <returns></returns>
    public async Task DeleteAsync(long dialogueId)
    {
        var knowledgeBase = await _dialogueRepository.GetByIdAsync(dialogueId);
        ExceptionHelper.ThrowIfNull(knowledgeBase, "对话不存在");
        await _dialogueRepository.DeleteAsync(knowledgeBase);
        await _medicalQuestionAnswerPairsRepository.DeleteAsync(x => x.DialogueId == dialogueId);
    }
}
